import axios from "axios";
import { Message } from "@garco-design/web-vue";
import { getToken, getEnv } from "@/utils/auth";

const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 120000,
});
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
      config.headers.env = `${getEnv()}`;
      config.baseURL = config.baseURL + `/${getEnv()}`;
    }
    // 判断参数是否为空
    if (config.method === "get") {
      const query = config.params;
      for (const key in query) {
        if (!query[key]) {
          delete query[key];
        }
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 响应拦截器
service.interceptors.response.use(
  function (response) {
    const res = response.data;
    if (res.code !== 200 && res.code !== 20000) Message.error(res.message || res.description);
    return res;
  },
  async function (error) { 
    // 对响应错误做点什么
    const { message, msg, description,code } = error.response.data;
    if ([40101, 40102].includes(code)) {
      clearToken();
      Message.error({
        content: description || msg || message || 'Request Error',
        duration: 2000,
      });
      window.location.reload();
    } else {
      Message.error({ content: description || msg || message || 'Request Error', duration: 2000 });
    }

    return Promise.reject(error);
  }
);
export default service;
